/*
 * Copyright (c) 2025 Huawei Technologies Co., Ltd.
 * openUBMC is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *         http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

#ifndef CX4_CARD_H
#define CX4_CARD_H

#include <mc/engine.h>
#include <mc/core/timer.h>
#include <ncsi_over_mctp/ncsi_over_mctp_mellanox.h>
#include <imu/imu.h>

#include "cx4_port.h"
#include "interface/board.h"
#include "interface/network_adapter.h"
#include "interface/network_adapter/cooling.h"
#include "interface/pcie_card.h"
#include "interface/pcie_device.h"
#include "interface/pcie_device/bandwidth.h"

namespace dev {
using ncsi_over_mctp_mellanox_ptr = std::shared_ptr<ncsi_over_mctp_mellanox>;
using imu_ptr               = std::shared_ptr<imu>;

class cx4_card : public mc::engine::object<cx4_card> {
public:
    MC_OBJECT(
        cx4_card, "PCIeNicCard", "/bmc/dev/Systems/1/PCIeNicCard/${object_name}",
        (PCIeDevice)(PCIeCard)(NetworkAdapter)(NetworkAdapter_Cooling)(Board)
        (PCIeDevice_Bandwidth))

    cx4_card();
    ~cx4_card();
    bool start();
    bool stop();
    bool init(mc::mutable_dict& csr_object, const mc::dict& connector);
    void init_network_ports();
    void update_ports_bdf_async(imu_pcie_device_req_t& pcie_device_info);
    void replace_dynamic_property(mc::mutable_dict& object, const mc::dict& connector);

    PCIeDevice                   m_pcie_device;
    PCIeCard                     m_pcie_card;
    NetworkAdapter_Cooling       m_network_adapter_cooling;
    NetworkAdapter               m_network_adapter;
    Board                        m_board;
    uint8_t                      m_system_id;
    PCIeDevice_Bandwidth   m_pcie_device_bandwidth;

private:
    std::vector<cx4_port*> m_network_ports;

    // ncsi over mctp 实现
private:
    bool                  start_ncsi_protocol();
    void                  stop_ncsi_protocol();
    void                  handle_os_reset();
    bool                  start_protocol();
    bool                  init_imu_protocol();
    imu_ptr               m_imu_obj;
    ncsi_over_mctp_mellanox_ptr m_ncsi_over_mctp_mellanox;
    mc::milliseconds      m_interval       = mc::milliseconds(5000); // ncsi over mctp 更新间隔5s
    mctp*                 m_mctp_object = nullptr; // 管理MCTP对象生命周期，防止内存泄漏
    uint8_t               m_package_id = 0;
};

} // namespace dev

#endif // __CX4_CARD_H__
